package cn.kgc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.kgc.entity.Admin;
import cn.kgc.form.AdminAddForm;
import cn.kgc.form.ResetPwdForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.interceptor.JwtInterceptor;
import cn.kgc.service.AdminService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.kgc.base.BaseInfoProperties.USER_ADMIN;

/**
 * @author YC
 */
@RestController
@RequestMapping("/user")
@Api(tags = "后台管理员模块")
@Validated
@Slf4j
public class AdminController {

    @Resource
    private AdminService adminService;

    /**
     * 判断是否重名
     */
    private boolean checkUserNameRepeat(String userName) {
        return adminService.count(new LambdaQueryWrapper<Admin>().eq(Admin::getUsername, userName)) > 0;
    }

    /**
     * 判断用户是否为管理员
     */
    private boolean checkUserTypeIsAdmin() {
        String adminId = JwtInterceptor.adminUserIds.get();
        if (adminId != null) {
            Admin admin = adminService.getById(adminId);
            return admin != null && admin.getUsername().equals(USER_ADMIN);
        }
        return false;
    }

    @PostMapping("/save")
    @ApiOperation("新增管理员用户")
    public GraceJSONResult save(@RequestBody AdminAddForm form) {
        log.debug("[params]新增管理员用户表单：{}", form);
        if (!checkUserTypeIsAdmin()) {
            return GraceJSONResult.errorMsg("不是管理员用户，权限不足");
        }
        if (checkUserNameRepeat(form.getUsername())) {
            return GraceJSONResult.errorMsg("用户名重复");
        }
        Admin admin = BeanUtil.copyProperties(form, Admin.class);
        admin.setPassword(BCrypt.hashpw(form.getPassword()));
        log.debug("[out]新增管理员实例：{}", admin);
        return GraceJSONResult.ok(adminService.save(admin));
    }

    @PostMapping("/delete")
    @ApiOperation("删除管理员用户")
    public GraceJSONResult delete(String id) {
        log.debug("[params]删除用户ID：{}", id);
        if (!checkUserTypeIsAdmin()) {
            return GraceJSONResult.errorMsg("不是管理员用户，权限不足");
        }
        String adminId = JwtInterceptor.adminUserIds.get();
        if (adminId.contains(id)) {
            return GraceJSONResult.errorMsg("不能删除当前登录用户");
        }
        return GraceJSONResult.ok(adminService.removeById(id));
    }

    @PostMapping("/resetpwd")
    @ApiOperation("重置管理员用户密码")
    public GraceJSONResult resetPassword(@RequestBody ResetPwdForm form) {
        String adminId = JwtInterceptor.adminUserIds.get();
        Admin admin = adminService.getById(adminId);
        if (BCrypt.checkpw(form.getOldPassword(), admin.getPassword())) {
            admin.setPassword(BCrypt.hashpw(form.getNewPassword()));
            return GraceJSONResult.ok(adminService.updateById(admin));
        }
        return GraceJSONResult.errorMsg("旧密码不正确");
    }

}

